package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by fish on 14-7-16.
 */
public class Biblioteca {
    private final IConsole console;
    private Library library;

    public Biblioteca(IConsole console, Library library) {
        this.console = console;
        this.library = library;
    }

    public void welcome() {
        console.writeLine("welcome to biblioteca!");
    }

    public IConsole getConsole() {
        return console;
    }

    public void run() {
        welcome();
//        listAllBooks();
        while(true) {
            menu();
            getUserOption();
        }
    }

    public void listAllBooks() {
        console.writeLine("                                Books In Library                                ");
        console.writeLine("================================================================================");
        console.writeLine("No.\tAuthor\tYear-Published\tTitle");
        for (Book book : library.getBookList()) {
            if(library.isBookAvailable(book.getTitle()))
            console.writeLine(book.displayString());
        }
    }

    public void menu() {
        console.writeLine("                                   Main Menu                                    ");
        console.writeLine("================================================================================");
        console.writeLine("                               [1] List Books");
        console.writeLine("                               [2] Reserve a book");
        console.writeLine("                               [3] Return a book");
        console.writeLine("                               [4] List Movies");
        console.writeLine("                               [5] Reserve a movie");
        if(library.getUserManager().getCurrentUser() == null)
        console.writeLine("                               [6] Log in");
        else console.writeLine("                               [6] Show My Info");
        console.writeLine("                               [0] Quit");
    }

    public void getUserOption() {
        final int optStart = 0;
        final int optEnd = 6;
        console.writeLine("Please input an option:");
        Scanner scanner = new Scanner(System.in);
        int opt = scanner.nextInt();
        while(opt<optStart || opt > optEnd) {
            console.writeLine("Select a valid option!");
            menu();
            console.writeLine("Please input an option:");
            opt = scanner.nextInt();
        }
        switch (opt) {
            case 1:
                listAllBooks();
                break;
            case 2:
                reserveBook();
                break;
            case 3:
                returnBook();
                break;
            case 4:
                listMovies();
                break;
            case 5:
                reserveMovie();
                break;
            case 6:
                if (library.getUserManager().getCurrentUser() == null)
                    logIn();
                else showUserInfo();
                break;
            default:
                System.exit(0);
                break;
        }
    }

    public Library getLibrary() {
        return library;
    }

    public void reserveBook() {
        console.writeLine("Please input a book title:");
        Scanner scanner = new Scanner(System.in);
        String title = scanner.nextLine();
        if(library.isBookAvailable(title)) {
            User currentUser = library.getUserManager().getCurrentUser();
            if(currentUser == null) {
                console.writeLine("you must log in before you reserve a book!");
                return;
            }
            Book searchedBook = library.getBookByTitle(title);
            if (searchedBook != null)
                library.getReservationManger().addReservation(searchedBook,currentUser);
            console.writeLine("Thank you! Enjoy the book");
        }
        else
            console.writeLine("That book is not available.");
    }

    public void returnBook() {
        console.writeLine("Please input book title:");
        Scanner scanner = new Scanner(System.in);
        String bookTitle = scanner.nextLine();
        if(library.isBookExist(bookTitle) && !library.isBookAvailable(bookTitle)) {
            User currentUser = library.getUserManager().getCurrentUser();
            if(currentUser == null) {
                console.writeLine("you must log in before you return a book!");
                return;
            }
            // deleting from reservation records.
            Book book = library.getBookByTitle(bookTitle);
            if(library.getReservationManger().getReservedBooks().get(book).equals(currentUser)) {
                library.getReservationManger().getReservedBooks().remove(book);
                console.writeLine("Thank you for returning the book.");
            }
            else console.writeLine("That is not a valid book to return.");
        }
        else console.writeLine("That is not a valid book to return.");
    }

    public void listMovies() {
        console.writeLine("                                Movies In Library                                ");
        console.writeLine("================================================================================");
        console.writeLine("Movie Name                    \tYear\tDirector Name       \tRate");
        for (Movie movie : library.getMovieList()) {
            if(library.isMovieAvailable(movie.getName()))
            console.writeLine(movie.displayString());
        }
    }

    public void reserveMovie() {
        console.writeLine("Please input a movie name:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        if(library.isMovieAvailable(name)) {
            User currentUser = library.getUserManager().getCurrentUser();
            if(currentUser == null) {
                console.writeLine("you must log in before you reserve a movie!");
                return;
            }
            Movie movie = library.getMovieByName(name);
            if (movie != null)
                library.getReservationManger().addReservation(movie,currentUser);
            console.writeLine("Thank you! Enjoy the movie!");
        }
        else
            console.writeLine("That movie is not available.");
    }

    public void logIn() {
        Scanner scanner = new Scanner(System.in);
        console.writeLine("Please input your library-number:");
        String libNum = scanner.nextLine();
        console.writeLine("Please input your password:");
        String password = scanner.nextLine();
        if(library.getUserManager().authenticate(libNum,password)) {
            library.getUserManager().setCurrentUser(library.getUserManager().getUserByLibnum(libNum));
            console.writeLine("successfully logged in.");
        } else {
            console.writeLine("Authentication failed!");
        }
    }

    public void showUserInfo() {
        User user = library.getUserManager().getCurrentUser();
        if(user != null) {
            String format = "%-20s\t%-14s\t%-20s\t%-11s";
            console.writeLine(String.format(format, "Name", "Library Number", "E-mail", "Phone"));
            console.writeLine(String.format(format,
                    user.getName(), user.getLibNumber(),user.getEmail(),user.getPhone()));
        }
        else console.writeLine("You must log in first!");
    }
}
